package JDBC_1.preparedstatement;

import JDBC_1.bean.Customer;
import JDBC_1.bean.Order;
import JDBC_1.util.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/5/13 10:33
 * @description： 使用PreparedStatement来实现针对于不同表的通用查询操作
 */
public class PreparedStatementQueryTest {
    @Test
    public void testgetForList(){
        String sql="select id,name,email from customers where id < ?";
        List<Customer> list = getForList(Customer.class, sql, 12);
        list.forEach(System.out::println);

        String sql1 = "select order_id orderId,order_name orderName,order_date orderDate from `order` where order_id < ?";
        List<Order> list1 = getForList(Order.class, sql1, 5);
        list1.forEach(System.out::println);
    }

    //查询多行
    public <T> List<T> getForList(Class<T> clazz, String sql, Object... args) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            //执行，获得结果集
            rs = ps.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            //获取字段据个数
            int columnCount = rsmd.getColumnCount();
            //创建集合对象
            ArrayList<T> list = new ArrayList<>();
            while (rs.next()) {
                //获取一个类的对象
                T t = clazz.newInstance();
                //给T对象复制的过程
                for (int i = 0; i < columnCount; i++) {
                    //获取每一个列的列值:通过resultset
                    Object columnValue = rs.getObject(i + 1);
                    //获取列的别名：getcolumnlabel（）推荐使用
                    String columnName = rsmd.getColumnLabel(i + 1);
                    //通过反射将对象指定属性名的属性赋值
                    Field field = clazz.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResourece(connection, ps, rs);
        }
        return null;
    }

    @Test
    public void testgetInstance() {
        String sql = "select id,name,email from customers where id = ?";
        Customer customer = getInstance(Customer.class, sql, 12);
        System.out.println(customer);

        String sql1 = "select order_id orderId,order_name orderName,order_date orderDate from `order` where order_id = ?";
        Order order = getInstance(Order.class, sql1, 1);
        System.out.println(order);
    }

    //利用反射技术来通过一个泛型的Class对象（也就是一个类），来返回一个对象
    public <T> T getInstance(Class<T> clazz, String sql, Object... args) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            //执行，获得结果集
            rs = ps.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            //获取字段据个数
            int columnCount = rsmd.getColumnCount();
            if (rs.next()) {
                //获取一个类的对象
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取每一个列的列值:通过resultset
                    Object columnValue = rs.getObject(i + 1);
                    //获取列的别名：getcolumnlabel（）推荐使用
                    String columnName = rsmd.getColumnLabel(i + 1);
                    //通过反射将对象指定属性名的属性赋值
                    Field field = clazz.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResourece(connection, ps, rs);
        }
        return null;
    }
}
